import React from 'react';
import PropTypes from 'prop-types';
import { gql, useQuery } from '@apollo/client';

import Loading from '@kuiper-components/loading';

import ChartPanel from '../ChartPanel';
import { name } from '../../../../../../package.json';

const QUERY_GQL = gql`
	query {
		JobMany(limit: 0) {
			note
			targetUrl
			target {
				hostname
				host
			}
			_id
			vulResult {
				_id
				result {
					warningCount
					warnings {
						_id
						level
					}
				}
			}
		}
	}
`;

const LEVEL_MAP = {
	3: '高',
	2: '中',
	1: '低',
};

export default function Vul({ className, data, jobs, taskIdMap, jobMap }) {
	const lastestCount = window?.kuiper?.app?.config[name]?.homeLastestCount;
	const { data: jobsData, loading } = useQuery(QUERY_GQL);

	const chartLineData = new Array(10).fill(0);

	for (let i = 0; i < data.length; i++) {
		for (let j = 0; j < lastestCount; j++) {
			chartLineData[j] = chartLineData[j] + (data[i][j]?.warnCount || 0);
		}
	}
	const lineData = chartLineData.reverse();

	const tableData = (jobsData?.JobMany || [])
		.map(item => {
			const levelObj = {};
			const target = item?.targetUrl;
			(item?.vulResult?.result?.warnings || []).forEach(item => {
				levelObj[item.level] = true;
			});
			const levelArr = Object.keys(levelObj)
				.sort((a, b) => b - a)
				.reduce((arr, x) => {
					arr.push(LEVEL_MAP[x]);
					return arr;
				}, []);
			return {
				target,
				note: item.note,
				level: levelArr.length > 0 ? levelArr.join('/') : '-',
				count: item?.vulResult?.result?.warningCount || 0,
				link: taskIdMap[target]?.vulResultId
					? `/weakness/vul/detail/${taskIdMap[target].vulResultId}`
					: undefined,
			};
		})
		.filter(x => x.count > 0)
		.sort((a, b) => b.count - a.count);

	const columns = [
		{ name: 'target', label: '监测资产' },
		{ name: 'level', label: '威胁等级' },
		{ name: 'count', label: '漏洞数量', width: 76 },
	];

	const total = tableData.reduce((res, { count }) => {
		res += count;
		return res;
	}, 0);

	return (
		<Loading hasData show={loading}>
			<ChartPanel
				key="vul"
				type="vul"
				className={className}
				title="Web漏洞"
				desc="以下数据为最新Web漏洞监测结果，按漏洞数从高到低排序。"
				link="/weakness/vul/overview"
				tableData={tableData}
				chartData={lineData}
				num={total}
				tooltipText="总资产最近十次监测结果趋势图"
				numLabel="漏洞总数"
				tableColumns={columns}
				chartLabel="Web漏洞趋势"
			/>
		</Loading>
	);
}

Vul.propTypes = {
	className: PropTypes.string,
	data: PropTypes.array,
	jobs: PropTypes.arrayOf(
		PropTypes.shape({
			target: PropTypes.shape({
				host: PropTypes.string,
			}),
		})
	),
	taskIdMap: PropTypes.object,
	jobMap: PropTypes.object.isRequired,
};
